let _loopDelay = 10
let __timerId: number | null | undefined = null
let id = 0
let sTime = 0

let tasks: any[] = []
class Time {
  static set delay(val) {
    if (typeof val !== 'number') throw new Error('定时时间必须为数字')
    _loopDelay = val
  }

  static get delay() {
    return _loopDelay
  }

  static init() {
    !__timerId && this.schedul()
  }

  static time() {
    return sTime / 1000 // 定时器启动时间
  }

  static schedul() {
    __timerId = setInterval(() => {
      sTime += _loopDelay
      for (let i = 0, len = tasks.length; i < len; i++) {
        const task = tasks[i]
        if (!task) continue
        if (task.once) {
          if (task.over) continue
          task.curTime += _loopDelay

          if (task.curTime >= task.delay) {
            task.over = true
            task && task()
          }
        }
        else {
          task.curTime += _loopDelay

          if (task.curTime >= task.delay) {
            task.curTime = 0
            task && task()
          }
        }
      }
    }, _loopDelay)
  }

  static once(task: { once: boolean }, delay = 1000) {
    task && (task.once = true)
    return this.addTask(task, delay)
  }

  static loop(task: any, delay = 1000) {
    return this.addTask(task, delay)
  }

  static addTask(task, delay) {
    if (typeof task !== 'function') throw new Error('必须传入函数')
    if (delay && typeof delay !== 'number') throw new Error('延迟时间必须传入数字，毫秒')
    delay = Math.max(delay, _loopDelay)

    task.id = id++
    task.delay = delay
    task.curTime = 0

    tasks.push(task)
    return id
  }

  static remove(tid) {
    if (typeof tid !== 'number') throw new Error('销毁定时器id必须为数字')
    const ind = tasks.find(t => t.id === tid)
    tasks.splice(ind, 1)
  }

  static stopAll() {
    clearInterval(__timerId)
    __timerId = null
  }

  static destory() {
    clearInterval(__timerId)
    __timerId = null
    tasks = []
    id = 0
  }
}

export default Time
